package com.paw.ruoyi.admin.core.util;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.paw.ruoyi.admin.common.constant.Constants;
import com.paw.ruoyi.admin.common.domain.Result;
import com.paw.ruoyi.admin.core.resource.IUploadFileResource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * 文件上传工具类
 * @author lvzihai
 * @date 2022/4/24
 **/
@Slf4j
public class FileUploadUtil {

  /**
   * 获取文件上传域名
   * 需要注册  IUploadFileResource的bean， 可以是feign的bean
   * @return
   */
  public static String getDomainUrl(){
    StringRedisTemplate redisTemplate = SpringUtil.getBean(StringRedisTemplate.class);
    if(redisTemplate==null){
      throw new RuntimeException("No bean found. StringRedisTemplate");
    }
    String key = "common:upload:domainUrl";
    String url = redisTemplate.opsForValue().get(key);
    if(url!=null){
      return url;
    }
    IUploadFileResource uploadFileResource = SpringUtil.getBean(IUploadFileResource.class);
    if(uploadFileResource==null){
      throw new RuntimeException("No bean found. IUploadFileResource");
    }
    Result<String> result = uploadFileResource.getDomainUrl();
    if(!(result.isSuccess() && StrUtil.isNotEmpty(result.getData()))){
      log.error("获取文件上传域名失败 {}", JSON.toJSONString(result));
      throw new RuntimeException("获取文件上传域名失败.");
    }
    url = result.getData();
    redisTemplate.opsForValue().set(key,url,1, TimeUnit.HOURS);

    return url;
  }


  /**
   * 获取不包含域名的key
   * @param url
   * @return
   */
  public static String getKey(String url){
    if(StrUtil.isEmpty(url)){
      return url;
    }
    return url.replaceAll(getDomainUrl(),"");
  }

  /**
   * 获取完整url
   * @param key
   * @return
   */
  public static String getUrl(String key){
    if(StrUtil.isEmpty(key)){
      return key;
    }
    String result = key;
    if(key.contains(",")){
      String[] keys = key.split(",");
      result = Arrays.stream(keys).filter(StrUtil::isNotEmpty)
          .map(item -> {
              if(item.startsWith(Constants.HTTP) || item.startsWith(Constants.HTTPS)){
                return item;
              }
              return getDomainUrl() + item;
            }
          )
          .collect(Collectors.joining(","));
    }else{
      if(!(key.startsWith(Constants.HTTP) || key.startsWith(Constants.HTTPS))){
        result = getDomainUrl()+key;
      }
    }

    return result;
  }
}
